package cn.mjnxin.iot.gate.sender;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

import cn.mjnxin.iot.base.log.LogWorker;
import cn.mjnxin.iot.base.util.MixUtil;
import cn.mjnxin.iot.gate.cache.GateRuntimeCache;
import io.netty.buffer.Unpooled;

/**
 * 十六进制发送
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class HexMessageSender implements Runnable{
    private final IChannelDataSender sender;

    public HexMessageSender(IChannelDataSender sender) {
        this.sender = sender;
    }
    
    @Override
    public void run() {
        printHelp();
        String hexStr = "";
    	Scanner selectInput = new Scanner(System.in);
        while(!"#".equals(hexStr)) {
        	try {
                hexStr = selectInput.nextLine();
        	}
        	catch(Exception ex) {
            	LogWorker.error(ex.getMessage(), ex);
        		selectInput.close();
        	}
            if ("*".equals(hexStr)) {
                printHelp();
                continue;
            }
            else if ("T".equals(hexStr)) {
            	sendSelect = hexStr;
        		Map<Integer, String[]> allTerminal = GateRuntimeCache.allTerminal();
                int index = 0;
                Map<Integer, Object[]> terminalList = new HashMap<>();
        		for (Iterator<Entry<Integer, String[]>> itr = allTerminal.entrySet().iterator(); itr.hasNext();) {
        			Entry<Integer, String[]> terminal = itr.next();
   	                for (String terminalKey : terminal.getValue()) {
						terminalList.put(index, new Object[] {terminal.getKey(), terminalKey});
   	        			System.out.println(String.format("%d 协议: %d 终端: %s", index, terminal.getKey(), terminalKey));
   	        			index++;
   	                }
        		}
                System.out.println("* 返回");
                Scanner selectClient = new Scanner(System.in);
            	try {
                    String select = selectClient.nextLine();
        	        while(!"*".equals(select)) {
        	        	try {
    	                    int i = Integer.parseInt(select);
    	                    if (i < 0 || i >= terminalList.size()) {
	        	        		System.err.println("输入数字不在范围内");
	       	                	select = selectClient.nextLine();
	       	                	continue;
	       	                }
    	                    Object[] terminal = terminalList.get(i);
	       	                pid = (Integer) terminal[0];
	       	                terminalAddress = (String) terminal[1];
	            			System.err.println(String.format("协议: %d 终端: %s 前置: %s", pid, terminalAddress, hostAddress));
	       	                break;
        	        	}
        	        	catch(Exception e) {
        	        		System.err.println("输入数字选择Client");
        	        		select = selectClient.nextLine();
        	        	}
        	        }
            	}
            	catch(Exception ex) {
                	LogWorker.error(ex.getMessage(), ex);
            		selectClient.close();
            	}
            }
            else if("M".equals(hexStr)) {
            	sendSelect = hexStr;
        		Map<Integer, String> allHost = GateRuntimeCache.allHost();
                int index = 0;
                List<Entry<Integer, String>> hostList = new ArrayList<Entry<Integer, String>>();
        		for (Iterator<Entry<Integer, String>> itr = allHost.entrySet().iterator(); itr.hasNext();) {
        			Entry<Integer, String> entry = itr.next();
        			hostList.add(entry);
        			System.out.println(String.format("%d 协议: %d 前置: %s", index++, entry.getKey(), entry.getValue()));
        		}
                System.out.println("* 返回");
            	Scanner selectHost = new Scanner(System.in);
            	try {
                    String select = selectHost.nextLine();
        	        while(!"*".equals(select)) {
        	        	try {
    	                    int i = Integer.parseInt(select);
    	                    if (i < 0 || i >= hostList.size()) {
	        	        		System.err.println("输入数字不在范围内");
	       	                	select = selectHost.nextLine();
	       	                	continue;
	       	                }
	       	                Entry<Integer, String> host = hostList.get(i);
	       	                pid = host.getKey();
	       	                hostAddress = host.getValue();
	            			System.err.println(String.format("协议: %d 终端: %s 前置: %s", pid, terminalAddress, hostAddress));
	       	                break;
        	        	}
        	        	catch(Exception e) {
        	        		System.err.println("输入数字选择Host");
        	        		select = selectHost.nextLine();
        	        	}
        	        }
            	}
            	catch(Exception ex) {
                	LogWorker.error(ex.getMessage(), ex);
            		selectHost.close();
            	}
            }
            else {
            	if (MixUtil.isHex(hexStr)) {
            		if (sendSelect.isEmpty() || pid == null)
            		{
            			printHelp();
            			continue;
            		}
            	    sendStart(hexStr);
            	}
            	else {
            		System.err.println("粘贴十六进制串发送报文");
            	}
            }
        }
    }
    
    private String  sendSelect    = "";
    private Integer pid           = null;
    private String  hostAddress   = "";
    private String  terminalAddress = "";
    
    private static void printHelp() {
        System.out.println("粘贴十六进制串发送报文");
        System.out.println("T 选择Terminal");
        System.out.println("H 选择Host");
        System.out.println("* 帮助");
        System.out.println("# 退出");
    }
    
    private void sendStart(String hexStr) {
        byte[] data  = MixUtil.hex2bytes(hexStr);
        try {
        	if ("T".equals(sendSelect)) {
        		if (terminalAddress.isEmpty())
        		{
            		printHelp();
        		}
                sender.sendTerminal(Unpooled.wrappedBuffer(data), pid, terminalAddress);
        	}
        	else if ("M".equals(sendSelect)) {
        		if (hostAddress.isEmpty() )
        		{
            		printHelp();
        		}
                sender.sendTerminal(Unpooled.wrappedBuffer(data), pid, hostAddress);
        	}
        	else {
        		printHelp();
        	}
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
